﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using Owin;
using Sharp.DataTransferObject;
using Sharp.Infrastructure.WebApiClient;
using Sharp.Portal.Mvc.OAuth.Baidu.Extensions;
using Sharp.Portal.Owin;
using Sharp.ServiceContracts;

namespace Sharp.WebBooter
{
    public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext<SharpUserManager>(SharpUserManager.Create);
            app.CreatePerOwinContext<SharpSignInManager>(SharpSignInManager.Create);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<SharpUserManager, SharpUser, int>(
                        TimeSpan.FromDays(7),
                        (manager, user) => user.GenerateUserIdentityAsync(manager),
                        id => int.Parse(id.GetUserId()))
                },
                //CookieHttpOnly = true,
                CookieName = "__SharpTicketSid",
                //SlidingExpiration = true,
                ExpireTimeSpan = TimeSpan.FromDays(7)
            });


            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(30));

            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            IList<OAuthConfigDTO> list;
            try
            {
                using (var proxy = new WebApiClientServiceProxy<IPlatformService>())
                {
                    list = proxy.Channel.GetOAuthConfigs();
                }
            }
            catch (Exception)
            {
                list = new List<OAuthConfigDTO>();
            }

            foreach (var config in list.Where(x =>
                x.IsEnable && x.AppId.IsNotNullOrEmpty() && x.AppSecret.IsNotNullOrEmpty() && x.Interface != OAuthConfigDTO.OAuthType.Platform))
            {
                switch (config.Interface)
                {
                    case OAuthConfigDTO.OAuthType.QQ:
                        app.UseQQAuthentication(config.AppId, config.AppSecret);
                        break;
                    case OAuthConfigDTO.OAuthType.Wechat:
                        app.UseWeChatAuthentication(config.AppId, config.AppSecret);
                        break;
                    case OAuthConfigDTO.OAuthType.Weibo:
                        app.UseWeiBoAuthentication(config.AppId, config.AppSecret);
                        break;
                    case OAuthConfigDTO.OAuthType.Baidu:
                        app.UseBaiduAuthentication(config.AppId, config.AppSecret);
                        break;
                    case OAuthConfigDTO.OAuthType.Platform:
                        app.UseSharpAuthentication(config.AppId, config.AppSecret);
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

            }
        }
    }
}
